package io.gitee.zhangbinhub.acp.boot.exceptions

import io.gitee.zhangbinhub.acp.boot.constant.AcpCoreConstant
import jakarta.servlet.Filter
import jakarta.servlet.FilterChain
import jakarta.servlet.ServletRequest
import jakarta.servlet.ServletResponse
import jakarta.servlet.annotation.WebFilter
import jakarta.servlet.http.HttpServletResponse
import org.springframework.core.annotation.Order

@WebFilter(urlPatterns = ["/**"])
@Order(AcpCoreConstant.SERVLET_ERROR_WEB_EXCEPTION_HANDLER_ORDER)
class ServletExceptionFilter(private val servletExceptionHandler: ServletExceptionHandler) : Filter {
    override fun doFilter(
        request: ServletRequest,
        response: ServletResponse,
        filterChain: FilterChain
    ) {
        try {
            filterChain.doFilter(request, response)
        } catch (e: Throwable) {
            if (response is HttpServletResponse) {
                servletExceptionHandler.responseGlobalException(response, e)
            } else {
                throw e
            }
        }
    }
}